package net.hn.hnms.biz.shipped.Listener;


import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.metadata.CellExtra;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import net.hn.hnms.biz.shipped.domain.TransportDeliveryStatistics;
import net.hn.hnms.biz.shipped.mapper.TransportDeliveryStatisticsMapper;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Slf4j
public class TransportDeliveryStatisticsListener implements ReadListener<TransportDeliveryStatistics> {

    /**
     * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 100;
    private List<TransportDeliveryStatistics> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
    private TransportDeliveryStatisticsMapper transportDeliveryStatisticsMapper;

    public TransportDeliveryStatisticsListener(TransportDeliveryStatisticsMapper transportDeliveryStatisticsMapper) {
        this.transportDeliveryStatisticsMapper = transportDeliveryStatisticsMapper;
    }

    /**
     * 假设这个是一个DAO，当然有业务逻辑这个也可以是一个service。当然如果不用存储这个对象没用。
     */
//    private UserDao userDao;
    @Override
    public void invoke(TransportDeliveryStatistics data, AnalysisContext context) {
        log.info("解析到一条数据:{}", JSON.toJSONString(data));
        if (StrUtil.isBlank(data.getDeptName()) || !data.getDeptName().equals("合计")) {
            cachedDataList.add(data);
            // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
            if (cachedDataList.size() >= BATCH_COUNT) {
                saveData();
                // 存储完成清理 list
                cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
            }
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        saveData();
        log.info("所有数据解析完成！");
    }

    @Override
    public void onException(Exception exception, AnalysisContext context) throws Exception {
        ReadListener.super.onException(exception, context);
    }

    @Override
    public void invokeHead(Map<Integer, ReadCellData<?>> headMap, AnalysisContext context) {
        log.info("解析到一条头数据:{}", JSON.toJSONString(headMap));

        Set[] i = new Set[]{headMap.keySet()};
        Arrays.stream(i).forEach(set -> {
            log.info(set.toString());
        });
        for (Set set : i) {
            log.info(set.toString());
        }
        System.out.println();
        // 如果想转成成 Map<Integer,String>
        // 方案1： 不要implements ReadListener 而是 extends AnalysisEventListener
        // 方案2： 调用 ConverterUtils.convertToStringMap(headMap, context) 自动会转换
    }

    @Override
    public void extra(CellExtra extra, AnalysisContext context) {
        ReadListener.super.extra(extra, context);
    }

    @Override
    public boolean hasNext(AnalysisContext context) {
        return ReadListener.super.hasNext(context);
    }


    private void saveData() {
        log.info("{}条数据，开始存储数据库！", cachedDataList.size());
//        userDao.save(cachedDataList);
        transportDeliveryStatisticsMapper.insertBatch(cachedDataList);
        log.info("存储数据库成功！");
    }
}
